from typing import Any
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.exceptions import RequestValidationError
from fastapi import status as fastapiStatus
from loguru import logger
from pydantic import ValidationError
from app.exceptions.exception import ParamException, BizException
from traceback import format_exc
from app.models.result import Result
from app.exceptions.status import Status


def register(app:FastAPI):
    @app.exception_handler(ParamException)
    async def param_exception_handler(request: Request, exc: ParamException):
        '''
        参数异常
        '''
        # logger.error(exc, exc_info=True, stack_info=True)
        logger.exception(exc)
        return Result(code=exc.code, message=exc.message)

    @app.exception_handler(BizException)
    async def biz_exception_handler(request: Request, exc: BizException):
        '''
        逻辑异常
        '''
        # logger.error(exc, exc_info=True, stack_info=True)
        logger.exception(exc)
        return Result(code=exc.code, message=exc.message)
    
    """请求参数异常"""
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Any, exc: Exception):
        # logger.error(exc, exc_info=True, stack_info=True)
        logger.exception(exc)
        return Result(code=fastapiStatus.HTTP_400_BAD_REQUEST, message='参数有问题')


    
    @app.exception_handler(StarletteHTTPException)
    async def custom_http_exception_handler(request: Request, exc: StarletteHTTPException):
        '''
        FastAPI异常
        '''
        # logger.error(exc, exc_info=True, stack_info=True)
        logger.exception(exc)
        return Result(code=exc.status_code, message=str(exc.detail))
    
    """捕获所有其他的异"""
    @app.exception_handler(Exception)
    async def exception_handler(request, exc: Exception):
        '''
        Exception
        '''
        # logger.error(exc, exc_info=True, stack_info=True)
        logger.exception(exc)
        response = JSONResponse(status_code=fastapiStatus.HTTP_500_INTERNAL_SERVER_ERROR,content=Result(code=Status.HTTP_FAIL.code, message='系统异常').__dict__)
        # return Result(code=Status.HTTP_FAIL.code, message='系统异常')
    
